<template>
  <div>
    <div class="app-page">
      <!-- <group-create ref="groupCreate" /> -->
      <!-- <div class="content"> -->
      <table-search
        :search-form="queryFormItem"
        :on-submit="handleQuery"
        :on-reset="handleQuery"
        :on-add="handleAdd"
      >
        <div slot="new-add-button" style="line-height:45px;">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAdd"
          >
            添加
          </el-button>
        </div>
      </table-search>
      <!-- </div> -->
    </div>
    <el-card class="table">
      <div class="app-btn-wrap  bottom_border" />
      <TablePaging
        :table-list="deviceList"
        border
        :table-column="deviceTableColumn"
        :table-buttons="deviceTableButtons"
        :table-btn-width="180"
        :table-paging="deviceTablePaging"
        :table-total="deviceTableTotal"
        @pagingChange="handlePaginChange"
      />
    </el-card>
    <!--  -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="
        () => {
          dialogVisible = false
        }
      "
    >
      <el-form ref="ruleForm" :model="formData1" :rules="rules">
        <el-form-item label="群组名称" prop="name" label-width="80px">
          <el-input v-model="formData1.name" placeholder="请输入群组名称" />
        </el-form-item>
      </el-form>
      <div class="group-dialog">
        <nav>
          <div
            :class="{ active: formData1.type === 1 }"
            @click="formData1.type = 1"
          >
            组织架构
          </div>
          <!-- <div
            :class="{ active: formData1.type === 2 }"
            @click="formData1.type = 2"
          >
            职务
          </div> -->
        </nav>
        <main v-if="formData1.type === 1">
          <div>
            <el-tree
              ref="tree"
              :data="treeData"
              show-checkbox
              node-key="id"
              @check-change="handleCheckChange"
            />
          </div>
          <footer>
            <div>
              <span>已选</span>
              <span>{{ selectPerson.length }}</span>
              <span>人：</span>
              <!-- v-for="(item, index) in selectPerson" :key="index" -->
              <span>
                {{ selectPerson.join('、') }}
              </span>
            </div>
          </footer>
        </main>
        <main v-else>
          <div>暂无数据</div>
        </main>
      </div>
      <div slot="footer">
        <el-button type="primary" size="small" @click="hnadleConfirm">
          确 定
        </el-button>
        <el-button
          size="small"
          @click="
            () => {
              dialogVisible = false
              flag = true
            }
          "
        >
          取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { groupFindPage, groupDelete } from '@/api/accountManage'
import { getDeptUserTree } from '@/api/commonTree'
import { groupAdd, groupGet, groupUpdate } from '@/api/group'
import { TableSearch, TablePaging } from '@/components'
// import GroupCreate from '@/containers/Group/create'
import { getAccountList } from '@/api/basiness'
import { queryFormItem, tableColumn } from './config'
import { formatTree } from '@/utils/index'
export default {
  name: 'Device',
  components: { TableSearch, TablePaging },
  data() {
    return {
      selectPerson: [],
      defaultChecked: [],
      rules: {
        name: [{ required: true, message: '请输入群组名称', trigger: 'blur' }]
      },
      formData1: {
        name: '',
        type: 1,
        userIds: []
      },
      treeData: [],
      treeDataUnformat: [],
      queryFormData: {},
      queryFormItem,
      deviceTableColumn: tableColumn(1, 10),
      deviceList1: [],
      deviceList: [{ name: '1', createTime: '时间' }],
      deviceTableButtons: [
        // 设备表操作按钮
        {
          name: '编辑',
          click: this.handleEdit
        },
        {
          name: '删除',
          confirm: '是否要删除？',
          click: this.handleDelete
        }
      ],

      deviceTableTotal: 0,
      deviceTablePaging: {
        page: 1,
        pagesize: 10
      },
      dialogTitle: '添加', // 弹窗标题
      dialogVisible: false, // 弹窗显示隐藏
      modalFormData: {}, // 弹窗表单数据
      deviceCodeDisabled: false, // 设备号是否禁止修改
      flag: true,
      handleType: 0
    }
  },
  created() {
    this.postFindPage()
    this.postReceiver()
  },
  methods: {
    handleQuery(values) {
      // 查询点击
      this.queryFormData = values
      this.deviceTablePaging = {
        page: 1,
        pagesize: 10
      }
      this.postFindPage()
    },

    // 新增 新增
    handleAdd() {
      this.formData1.name = ''
      this.formData1.userIds = []
      this.selectPerson = []
      this.getDeptUserTreeData()
      this._setModalData('新建群组', true, {})
      // this.$refs.groupCreate.open().then(val => {
      //   this.postFindPage()
      // })
    },
    // 修改,编辑
    handleEdit(id) {
      this._setModalData('编辑群组', true)
      this.getDeptUserTreeData(id)
      this.flag = false
      this.handleType = 1
    },

    handleDelete(id) {
      this.postDeviceDelete(id)
    },

    handleModalSubmit(values) {
      console.log(values)
      // 弹窗表单提交
      // if (values.id) {
      //   this.postDeviceUpdate(values)
      //   return false
      // }
      // this.postDeviceAdd(values)
    },

    handlePaginChange(pageInfo) {
      // 分页改变
      this.deviceTablePaging = pageInfo
      this.postFindPage()
      const { page, pagesize } = pageInfo
      this.deviceTableColumn = tableColumn(page, pagesize)
    },

    _setModalData(title = '添加', visible = true, formData = {}) {
      // 设置弹窗
      // this.formData1 = formData
      this.dialogTitle = title
      this.dialogVisible = visible
      this.deviceCodeDisabled = title !== '添加'
    },
    fetchGroupGet(id) {
      groupGet({ id }).then(res => {
        const { name, type, userIdList, id } = res
        this.formData1.name = name
        this.formData1.type = type
        this.formData1.userIds = userIdList
        this.$set(this.formData1, 'id', id)
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(this.formData1.userIds)
          this.handleCheckChange()
        })
        this.handleType = 0
      })
    },

    // 获取列表
    postFindPage() {
      groupFindPage({
        ...this.queryFormData,
        ...this.deviceTablePaging
      }).then(res => {
        const { records, current, size, total } = res
        this.deviceList = records
        this.deviceTablePaging = {
          page: current,
          pagesize: size
        }
        this.deviceTableTotal = total
      })
    },

    postDeviceAdd() {
      // 设备新增
      groupAdd(this.formData1).then(res => {
        this.dialogVisible = false
        this.$message({
          type: 'success',
          message: '添加成功'
        })
        this.formData1.name = ''
        this.formData1.userIds = []
        this.formData1.type = 1
        this.postFindPage()
      })
    },
    // 设备更新
    postDeviceUpdate() {
      groupUpdate(this.formData1).then(() => {
        this.dialogVisible = false
        this.$message({
          type: 'success',
          message: '修改成功'
        })
        this.postFindPage()
      })
    },
    // 设备删除
    postDeviceDelete(id) {
      groupDelete({ id }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.postFindPage()
      })
    },
    postReceiver() {
      getAccountList().then(val => {
        const res = val.map(e => ({ key: e.id, value: e.name }))
        this.queryFormItem.forEach(obj => {
          for (const key in obj) {
            if (obj[key] === 'userId') {
              this.$set(obj, 'options', res)
            }
          }
        })
      })
    },
    // 树 被勾选
    handleCheckChange(e) {
      const checkedTreeNode = this.$refs.tree.getCheckedNodes()
      this.formData1.userIds = []
      this.selectPerson = []
      checkedTreeNode.forEach(item => {
        if (item.type === 5) {
          if (!this.formData1.userIds.includes(item.id)) {
            this.formData1.userIds.push(item.id)
            this.selectPerson.push(item.label)
          }
        }
      })
    },
    // 组织架构树 数据
    getDeptUserTreeData(id) {
      getDeptUserTree({ deptType: 0, userType: 0 }).then(val => {
        const res = val.map(e => ({
          label: e.name,
          id: e.id,
          parentDeptId: e.parentDeptId,
          type: e.type
        }))
        this.treeDataUnformat = res
        this.treeData = formatTree(res, '_')
        if (this.handleType === 1) {
          this.fetchGroupGet(id)
          return
        }
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(this.formData1.userIds)
        })
      })
    },
    // 点击确定
    hnadleConfirm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.formData1.userIds.length === 0) {
            this.$message({
              message: '请至少选一个人',
              type: 'warning'
            })
            return
          }
          if (this.flag) {
            this.postDeviceAdd()
            this.flag = true
          } else {
            this.postDeviceUpdate()
            this.flag = true
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
.app-page {
  min-height: 0;
}
.table {
  margin-top: 20px;
}
/deep/ .el-form-item__label {
  font-weight: 400;
}
</style>
